package com.github.editor.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PngUtil {
    public static boolean resize(String input, String savePath, int newWidth, int newHeight) {
        File fromFile = new File(input);
        if (!fromFile.exists()) {
            return false;
        }
        File toFile = new File(savePath);
        BufferedImage srcImage = null;
        try {
            srcImage = ImageIO.read(fromFile);
        } catch (Throwable e) {
            return false;
        }
        int startX, startY;
        int scaleWidth, scaleHeight;
        double srcWidth = srcImage.getWidth(null);
        double srcHeight = srcImage.getHeight(null);
        double rate1 = srcWidth / (double) newWidth;
        double rate2 = srcHeight / (double) newHeight;
        double rate = Math.min(rate1, rate2);
        double width = Math.round((float) (srcWidth / rate));
        double height = Math.round((float) (srcHeight / rate));
        double target = Math.min(width, height);
        startX = Math.round((float) (width - target) / 2.0f);
        startY = Math.round((float) (height - target) / 2.0f);
        scaleWidth = newWidth + startX * 2;
        scaleHeight = newHeight + startY * 2;
//        System.out.println("size=" + srcWidth + "x" + srcHeight + "->" + scaleWidth + "x" + scaleHeight + ", start=" + startX + "x" + startY);

        BufferedImage dstImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = dstImage.createGraphics();
        Image from = srcImage.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_AREA_AVERAGING);
        g2d.drawImage(from, -startX, -startY, null);//居中裁剪
        g2d.dispose();
        try {
            ImageIO.write(dstImage, "png", toFile);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
